import { useRequest } from 'ahooks';
import { parse } from 'querystring';
import React, { createContext, useContext, useEffect, useState } from 'react';

import { ActivityInfo, Goods } from '@/types/apiType';

import { apiActivityInfoByGet, apiGoodsInfoByGet } from '../apis/formatApi';
import { apiM1SpreadGetSpreadKeyByGet } from '../apis/m1Spread';
import { apiWinUnReceiveCountByGet } from '../apis/win';
import { useUser } from '../hooks/use-user';

interface GlobalContextValue {
  activityInfo: ActivityInfo | undefined;
  goodInfo: Goods | undefined;
  unReceiveCount: number | undefined;
  spreadKey?: string | undefined;
}

export const GlobalContext = createContext<GlobalContextValue>({
  activityInfo: {},
  goodInfo: {},
  unReceiveCount: 0
});

interface GlobalProviderProps {
  children: React.ReactNode;
}
export let globalValue: any = {};
/**
 * 全局配置
 *
 */
export const GlobalProvider: React.FC<GlobalProviderProps> = ({ children }) => {
  const { data: activityInfo, refresh: refreshActive } = useRequest<ActivityInfo, any>(
    apiActivityInfoByGet,
    { manual: true }
  );

  const { data: goodInfo, refresh } = useRequest(
    () => apiGoodsInfoByGet({ activityId: activityInfo?.id as number }),
    {
      manual: true
    }
  );

  const { data: unReceiveCount, refresh: refreshUnReceiveCount } = useRequest(
    () => apiWinUnReceiveCountByGet(),
    {
      manual: true
    }
  );
  const { user } = useUser();

  /**
   * 获取推广key
   */
  const { data: spreadKey, refresh: getSpreadKey } = useRequest(
    () =>
      apiM1SpreadGetSpreadKeyByGet({
        activityId: activityInfo?.id as number,
        goodsId: goodInfo?.id as number
      }),
    { manual: true }
  );
  useEffect(() => {
    if (user?.token) {
      refreshActive();
      refreshUnReceiveCount();
    }
  }, [user]);

  useEffect(() => {
    if (activityInfo?.id) {
      refresh();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activityInfo]);

  useEffect(() => {
    if (activityInfo?.id && goodInfo?.id) getSpreadKey();
  }, [activityInfo, goodInfo]);

  globalValue = {
    spreadKey,
    activityInfo,
    goodInfo,
    unReceiveCount
  };
  return <GlobalContext.Provider value={globalValue}>{children}</GlobalContext.Provider>;
};

export const useGlobal = () => useContext(GlobalContext);
